use std::sync::Arc;

use anyhow::Ok;
use lazy_static::lazy_static;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use tokio::sync::OnceCell;

lazy_static! {
    static ref DB_CONNN: Arc<OnceCell<DatabaseConnection>> = Arc::new(OnceCell::new());
}
pub async fn init_db() -> anyhow::Result<()> {
    // 数据库连接
    let database_url = std::env::var("DATABASE_URL")?;
    let mut opt = ConnectOptions::new(&database_url);
    opt.max_connections(1)
        .sqlx_logging(true)
        .sqlx_logging_level(log::LevelFilter::Debug);
    let conn = Database::connect(opt).await?;
    DB_CONNN.set(conn)?;
    // Ok(conn)
    Ok(())
}

/// 获取数据库连接
pub fn get_conn() -> DatabaseConnection {
    DB_CONNN.get().unwrap().clone()
}
